package com.ruoyi.project.module.ossconfig.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.module.ossconfig.domain.OSSConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.module.ossconfig.service.IOSSConfigService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;

import javax.xml.bind.JAXBException;

/**
 * 阿里云OSS资源 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-04-08
 */
@Controller
@RequestMapping("/module/ossconfig")
public class OSSConfigController extends BaseController
{
    private String prefix = "module/ossconfig";
	
	@Autowired
	private IOSSConfigService configService;



	/**
	 * 修改配置组
	 */
	@GetMapping("/copy/{uniqueId}")
	public String copy(@PathVariable("uniqueId") Long uniqueId, ModelMap mmap)
	{
		OSSConfig model = configService.selectConfigById(uniqueId.intValue());
		mmap.put("model", model);
		return prefix + "/copy";
	}


	/**
	 * 复制保存配置组
	 */
	@RequiresPermissions("module:group:add")
	@Log(title = "配置组", businessType = BusinessType.INSERT)
	@PostMapping("/copy")
	@ResponseBody
	public AjaxResult copySave(Long sourceConfigGroupId,OSSConfig ossConfig)
	{
		return toAjax(configService.copyModel(sourceConfigGroupId,ossConfig));
	}



	@RequiresPermissions("module:ossconfig:view")
	@GetMapping()
	public String config()
	{
	    return prefix + "/ossconfig";
	}
	
	/**
	 * 查询阿里云OSS资源列表
	 */
	@RequiresPermissions("module:ossconfig:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(OSSConfig OSSConfig)
	{
		startPage();
        List<OSSConfig> list = configService.selectConfigList(OSSConfig);
		return getDataTable(list);
	}
	
	/**
	 * 新增阿里云OSS资源
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存阿里云OSS资源
	 */
	@RequiresPermissions("module:ossconfig:add")
	@Log(title = "阿里云OSS资源", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(OSSConfig OSSConfig)
	{		
		return toAjax(configService.insertConfig(OSSConfig));
	}

	/**
	 * 修改阿里云OSS资源
	 */
	@GetMapping("/edit/{ossConfigId}")
	public String edit(@PathVariable("ossConfigId") Integer ossConfigId, ModelMap mmap)
	{
		OSSConfig OSSConfig = configService.selectConfigById(ossConfigId);
		mmap.put("OSSConfig", OSSConfig);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存阿里云OSS资源
	 */
	@RequiresPermissions("module:ossconfig:edit")
	@Log(title = "阿里云OSS资源", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(OSSConfig OSSConfig)
	{		
		return toAjax(configService.updateConfig(OSSConfig));
	}
	
	/**
	 * 删除阿里云OSS资源
	 */
	@RequiresPermissions("module:ossconfig:remove")
	@Log(title = "阿里云OSS资源", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(configService.deleteConfigByIds(ids));
	}


	/**
	 * 修改阿里云OSS资源
	 */
	@GetMapping("/content/{ossConfigId}")
	public String content(@PathVariable("ossConfigId") Integer ossConfigId, ModelMap mmap)
	{
		OSSConfig OSSConfig = configService.selectConfigById(ossConfigId);
		mmap.put("OSSConfig", OSSConfig);
		return prefix + "/content";
	}

	/**
	 * 修改保存阿里云OSS资源
	 */
	@RequiresPermissions("module:ossconfig:release")
	@Log(title = "阿里云OSS资源", businessType = BusinessType.UPDATE)
	@PostMapping("/content")
	@ResponseBody
	public AjaxResult contentSave(OSSConfig ossConfig)
	{

		if (StringUtils.isEmpty(ossConfig.getFileContentStr())) {

			return error("内容不能为空");
		}

		OSSConfig ocTemp = configService.selectConfigById(ossConfig.getOssConfigId());
		if("application/json".equalsIgnoreCase(ocTemp.getOssContentType())){
		    try{
				 JSONObject.parseObject(ossConfig.getFileContentStr());
			}catch (Exception e){
				String message = e.getMessage();
				return error("文件内容非json正确格式:"+message);
			}
		}


	    OSSConfig temp=new OSSConfig();
	    temp.setFileContentStr(ossConfig.getFileContentStr());
	    temp.setOssConfigId(ossConfig.getOssConfigId());
		return toAjax(configService.updateConfig(temp));
	}


	/**
	 * 上传至阿里云
	 * @throws IOException
	 */
	@Log(title = "错误代码JSON生成", businessType = BusinessType.GENCODE)
	@RequestMapping("/release/{ossConfigId}")
	@ResponseBody
	public AjaxResult release(@PathVariable("ossConfigId") Integer ossConfigId, ModelMap mmap) throws IOException {
		OSSConfig ossconfig = configService.selectConfigById(ossConfigId);



		if(ossconfig.getEndpoint()==null){
			return error("Endpoint不能为空");
		}
		if(ossconfig.getAccessKeyId()==null){
			return error("AccessKeyId不能为空");
		}
		if(ossconfig.getSecretAccessKey()==null){
			return error("SecretAccessKey不能为空");
		}
		if(ossconfig.getBucketName()==null){
			return error("BucketName不能为空");
		}
		if(ossconfig.getFileContentStr()==null){
			return error("FileContentStr不能为空");
		}
		if(ossconfig.getFileName()==null){
			return error("FileName不能为空");
		}
		if(ossconfig.getOssContentType()==null){
			return error("OssContentType不能为空");
		}
		OSSClient ossClient=null;
		StringBuilder sb=new StringBuilder("上传成功");
		try{
			ossClient= new OSSClient(ossconfig.getEndpoint(), ossconfig.getAccessKeyId(), ossconfig.getSecretAccessKey());

			//创建上传Object的Metadata
			ObjectMetadata metadata = new ObjectMetadata();
			//上传的文件的长度
			InputStream inputStream=new ByteArrayInputStream(ossconfig.getFileContent());

			metadata.setContentLength(inputStream.available());
			//指定该Object被下载时的网页的缓存行为
//			metadata.setCacheControl("no-cache");
			metadata.setCacheControl("max-age=1");
			//指定该Object下设置Header
			metadata.setHeader("Pragma", "no-cache");
			metadata.setHeader("Expires", "1");
			//指定该Object被下载时的内容编码格式
			metadata.setContentEncoding("UTF-8");
			//文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
			//如果没有扩展名则填默认值application/octet-stream
			metadata.setContentType(ossconfig.getOssContentType());
			//上传文件   (上传文件流的形式)
			PutObjectResult putResult = ossClient.putObject(ossconfig.getBucketName(),ossconfig.getFileName(), inputStream,metadata);
//			sb.append(putResult.getETag());
		}catch (Exception e){
		    throw e;
		}finally {
			ossClient.shutdown();
		}


		return success(sb.toString());
	}


}
